package com.company.JUC.ref可见性;

import java.time.Instant;
import java.util.concurrent.TimeUnit;

/**
 * @Classname MyCircularQueue
 * @Description TODO
 * @Date 2021/8/10 9:51
 * @Created by ylr
 */
public class Main {
    private static Pet pet = new Pet("dahuang", 1);


    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println("t1 start " + Instant.now());
//            Pet A = new Pet("a", 1);
//            pet = A;
//            System.out.println(pet);
            while (true) {
                if (pet.getAge() == 5) {
                    break;
                }
            }
            System.out.println("t1 end " + Instant.now());
        }, "t1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            System.out.println("t2 start " + Instant.now());
//
//            Pet B = new Pet("b", 2);
//            pet = B;
//            System.out.println(pet);
//            Pet myPet = pet;
            for (int i = 1; i <= 100; i++) {
//                int age = pet.getAge();
                pet.setAge(i);
                /*try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
            }
            System.out.println("t2 end " + Instant.now());
        }, "t2").start();
    }

    static class Pet {
        String name;

        volatile int age;

        public Pet(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public  void setName(String name) {
            this.name = name;
        }

        public synchronized int getAge() {
            return age;
        }

        public synchronized void setAge(int age) {
            this.age = age;
        }
    }
}
